import json

from django.core.cache import cache
from django.http import HttpResponse
from django.shortcuts import render, redirect

from rest_framework.renderers import JSONRenderer
from rest_framework.views import APIView

from common.forms import RegisterForm
from common.models import Province, User
from common.models import City
from common.models import District
from common.serializers import ProvinceSerializer
from common.serializers import CitySerializer
from common.serializers import DistrictSerializer
from common.utils import to_md5_hex
from common.utils import gen_mobile_code
from fang.tasks import send_short_message


def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        username = request.POST['username']
        password = request.POST['password']
        code = request.POST['code']
        try:
            if code == request.session['code']:
                try:
                    user = User.objects.get(username=username)
                    if user and user.password == to_md5_hex(password):
                        request.session['user_id'] = user.user_id
                        request.session['user_realname'] = user.real_name
                        return redirect('index')
                    else:
                        hint = '用户名或密码错误'
                except User.DoesNotExist:
                    hint = '用户名或密码错误'
            else:
                hint = '请输入正确的验证码'
        except KeyError:
            hint = '请先获取验证码再完成登录'
    return render(request, 'login.html', {'hint': hint})


def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    else:
        form = RegisterForm(request.POST)
        if form.is_valid():
            if form.cleaned_data['code'] == request.session['code']:
                form.save()
                return render(request, 'login.html', {'hint': '注册成功请登录'})
            else:
                hint = '请输入有效的手机验证码'
        else:
            hint = form.errors
    return render(request, 'register.html', {'hint': hint})


def send_code(request, mobile):
    code = gen_mobile_code()
    send_short_message.delay(mobile, code)
    request.session['code'] = code
    cache.set(mobile, code, nx=True, timeout=60)
    return HttpResponse(json.dumps({'code': 2}), content_type='application/json; charset=utf-8')


# class ProvinceView(APIView):
#
#     def get(self, request, formatter=None):
#         pass
#
#     def post(self, request, formatter=None):
#         pass


class JSONResponse(HttpResponse):

    def __init__(self, data, **kwargs):
        renderer = JSONRenderer()
        renderer.ensure_ascii = True
        content = renderer.render(data)
        # content = json.dumps(data)
        kwargs['content_type'] = 'application/json; charset=utf-8'
        super(JSONResponse, self).__init__(content, kwargs)


def get_all_provinces(request):
    serializer = ProvinceSerializer(Province.objects.all(), many=True)
    return JSONResponse(serializer.data)


def get_cities(request, prov_id):
    serializer = CitySerializer(City.objects.filter(prov__prov_id=prov_id), many=True)
    return JSONResponse(serializer.data)


def get_districts(request, city_id):
    serializer = DistrictSerializer(District.objects.filter(city__city_id=city_id), many=True)
    return JSONResponse(serializer.data)
